import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_pad_widgets/config/kq_pad_global.dart';

import '../../resources/images.dart';
import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../dialog/kq_pad_file_picker.dart';
import '../divider/kq_pad_divider.dart';
import 'entity/kq_form_entity.dart';

class KqPadImageBoxItemView extends StatefulWidget {
  /// 数据实体类
  final KqPadFormEntity entity;

  /// 图片添加按钮点击回调
  final Function(KqPadFormEntity entity, KqImageBoxState state)? onAddTap;

  /// 图片删除按钮点击回调
  final Function(KqPadFormEntity entity, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onDeleteTap;

  /// 图片点击回调
  final Function(KqPadFormEntity entity, ImageUrl imageUrl, int position,
      KqImageBoxState state)? onImageTap;

  const KqPadImageBoxItemView(
      {Key? key,
      required this.entity,
      this.onAddTap,
      this.onDeleteTap,
      this.onImageTap})
      : super(key: key);

  @override
  KqPadImageBoxItemViewState createState() => KqPadImageBoxItemViewState();
}

class KqPadImageBoxItemViewState extends State<KqPadImageBoxItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 拼接提交的valueForSubmit
  String? getSubmitValues({join = ','}) {
    if (widget.entity.imageUrls == null || widget.entity.imageUrls!.isEmpty) {
      return null;
    }
    var values = [];
    for (var url in widget.entity.imageUrls!) {
      if (url.valueForSubmit != null) {
        values.add(url.valueForSubmit);
      }
    }
    return values.isEmpty ? null : values.join(join);
  }

  double titleWidth = 0;

  calTitleWidth() {
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }
    titleWidth = measureTextWidth(titleWidthString, textStyle: titleStyle);
  }

  @override
  void didUpdateWidget(covariant KqPadImageBoxItemView oldWidget) {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor;

    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                top: widget.entity.paddingVertical ?? 9.dm,
                bottom: widget.entity.paddingVertical ?? 9.dm,
                right: widget.entity.paddingHorizontal ??
                    KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    16.dm),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                /// 是否必填
                Container(
                  alignment: Alignment.centerRight,
                  width: widget.entity.paddingHorizontal ??
                      KqPadThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      8.dm,
                  padding: EdgeInsets.only(right: 1.dm),
                  child: Text(
                    "∗",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: KqPadThemeManager.instance
                                .getConfig()
                                .formConfig
                                .mustInputFontSize ??
                            7.dm,
                        color: widget.entity.mustInput
                            ? KqPadThemeColors.textRed
                            : widget.entity.mustInputStarColor ??
                                KqPadThemeColors.bgTransparent),
                  ),
                ),

                Container(
                  width: titleWidth + 6.dm,
                  padding: EdgeInsets.only(right: 6.dm, top: 0.5.dm),
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      /// 左边自定义控件
                      /// 自定义布局，来自实体类
                      widget.entity.customLeftView != null
                          ? widget.entity.customLeftView!(widget.entity)
                          : Container(),

                      if (widget.entity.title.isNotEmpty)
                        Expanded(
                          child: Text(
                            widget.entity.title.fixSoftWrap() ?? '',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            textAlign: widget.entity.titleTextAlign,
                            style: titleStyle,
                          ),
                        ),
                    ],
                  ),
                ),

                /// 图片容器
                widget.entity.imageUrls == null ||
                        (widget.entity.imageUrls!.isEmpty &&
                            !widget.entity.isEditable())
                    ? Container()
                    : Expanded(
                        child: Container(
                          color: bgColor,
                          child: KqImageBox(
                            urls: widget.entity.imageUrls!,
                            maxQty: widget.entity.maxQty?.toInt() ?? 8,
                            cols: widget.entity.imageBoxCols,
                            customAddPic: Images.commonPicUpload88,
                            customAddPicPackage: KqPadGlobal.packageName,
                            onAddTap: (urls, state) {
                              if (widget.entity.onAddTap == null &&
                                  widget.onAddTap == null) {
                                //默认点击添加按钮实现
                                KqPadFilePicker(
                                        maxCount:
                                            (widget.entity.maxQty?.toInt() ??
                                                    8) -
                                                state.count())
                                    .choosePhoto(
                                  context,
                                  (files) {
                                    for (var file in files) {
                                      state.addImage(ImageUrl(
                                          imageType: ImageType.file,
                                          url: file.filePath!));
                                    }
                                  },
                                );
                                return;
                              }
                              if (widget.entity.onAddTap != null) {
                                widget.entity.onAddTap!(widget.entity, state);
                              }
                              if (widget.onAddTap != null) {
                                widget.onAddTap!(widget.entity, state);
                              }
                            },
                            onDeleteTap: (urls, imageUrl, position, state) {
                              if (widget.entity.onDeleteTap == null &&
                                  widget.onDeleteTap == null) {
                                state.remove(imageUrl);
                                return;
                              }
                              if (widget.entity.onDeleteTap != null) {
                                widget.entity.onDeleteTap!(
                                    widget.entity, imageUrl, position, state);
                              }
                              if (widget.onDeleteTap != null) {
                                widget.onDeleteTap!(
                                    widget.entity, imageUrl, position, state);
                              }
                            },
                            onImageTap: (urls, imageUrl, position, state) {
                              if (widget.entity.onImageTap == null &&
                                  widget.onImageTap == null) {
                                FilePreviewUtil.previewImg(
                                    widget.entity.imageUrls!);
                                return;
                              }
                              if (widget.entity.onImageTap != null) {
                                widget.entity.onImageTap!(
                                    widget.entity, imageUrl, position, state);
                              }
                              if (widget.onImageTap != null) {
                                widget.onImageTap!(
                                    widget.entity, imageUrl, position, state);
                              }
                            },
                            onChanged: () {
                              setState(() {});
                            },
                            editable: widget.entity.isEditable(),
                          ),
                        ),
                      ),
              ],
            ),
          ),

          /// 分割线
          Visibility(
              visible: !widget.entity.isEditable(),
              child: const KqPadDivider()),

          /// 分隔栏
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
          Visibility(
              visible: widget.entity.showDivider2, child: const KqPadDivider()),
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
        ],
      ),
    );
  }

  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }
}
